<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use fast\Random;
use think\Db;
use think\Session;

use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;

use app\common\model\User as UserModel;
use app\common\model\UserHistory as UserHistoryModel;
use app\common\model\Sysmessage as SysmessageModel;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $password = '123456';
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }

        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), 0, ['class' => 'form-control selectpicker']));
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    /**
     * 学员导入提交
     * @return string|void
     */
    public function import()
    {
        if ($this->request->isPost()) {
            // 加载数据
            $insert = Session::pull('import_student');
            if (!$insert) {
                $this->error(__('没有可以导入的数据，请重新上传Excel文件'));
            }
            
            try {
                $this->model->saveAll($insert);
            } catch (PDOException $exception) {
                $msg = $exception->getMessage();
                if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                    $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
                };
                $this->error($msg);
            } catch (\Exception $exception) {
                $this->error($exception->getMessage());
            }
            
            $this->success();
        }
        
        $groupList = \app\common\model\UserGroup::where('status','normal')->order('id DESC')->select();
        $this->view->assign('groupList', $groupList);
        return $this->view->fetch();
    }
    
    
    /**
     * 学员导入
     */
    public function importExcel()
    {
        if ($this->request->isPost()) {
            
            $cate = $this->request->param('cate');
            if (!$cate) {
                $this->error('请先选择所属分组再进行上传');
            }
            
            
            $file = $this->request->request('file');
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }
            
            $filePath = ROOT_PATH . DS . 'public' . DS . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            
            
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            
     

            if ($ext === 'csv') {
                $file     = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp       = fopen($filePath, "w");
                $n        = 0;
                while ($line = fgets($file)) {
                    $line     = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);
                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }
                    
                    
            //加载文件
            $insert = [];
            try {
                
                if (!$PHPExcel = $reader->load($filePath)) {
                    throw new \Exception(__('Unknown data format'));
                }
                
                $currentSheet    = $PHPExcel->getSheet(0);                //读取文件中的第一个工作表
                $allColumn       = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow          = $currentSheet->getHighestRow();        //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
        
                
                $fields = [
                    'username',
                    'mobile',
                    'gender',
                    'nickname',
                    'email',
                    // 'birthday',
                    'password',
                    // 'avatar',
                    // 'bio',
                    'status'
                ];
                
                $password = $this->password;

                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val      = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $values[] = is_null($val) ? '' : $val;
                        
                    }
                    // $temp    = array_combine($fields, $values);
                    $row     = [];
                    $options = [];

                    // 选项及字段组合
                    for ($i = 0; $i < min($maxColumnNumber, count($fields)); $i++) {
                        $field = $fields[$i];
                        $value = $values[$i];
                        
                        if ($i > 9) {
                            if (!empty($value) || $value == '0') {
                                $options[$field] = $value;
                            }
                        } else {
                            $row[$field] = $value;
                        }
                    }
                    
                    // 过滤空行
                    if (!$row['username']) {
                        continue;
                    }
                    // 特殊字段处理
                    foreach ($row as $key => $item) {
                        
                        if ($key == 'gender') {
                            switch ($item) {
                                case '男':
                                    $item = 1;
                                    break;
                                case '女':
                                    $item = 0;
                                    break;
                                default:
                                    // code...
                                    break;
                            }
                        }
                        // if($key == 'birthday'){
                        //     $item = $item ? date('Y-m-d',strtotime($item)) : null;
                        // }
                        if($key == 'password'){
                            $salt = Random::alnum();
                            $password = $item ? $item : $this->password;
                            $item = Auth::instance()->getEncryptPassword($password, $salt);
                            $row['salt']     = $salt;
                        }
                        if($key == 'status'){
                            $item = $item ? $item : '正常';
                            $selects = ['正常'=>'normal','隐藏'=>'hide'];
                            $item = $selects[$item];
                        }
                        $row[$key]   = $item;
                    }
                    

                    $row['group_id'] = $cate;
                    $row['status']   = 'normal';
                    $insert[] = $row;
                }
                
                $mobile_ids = array_column($insert,'mobile');
                if(count($mobile_ids) != count(array_unique($mobile_ids))){
                    throw new \Exception(__('导入模板手机号码重复'));
                }
                $is_mobile = $this->model->where('mobile','IN',$mobile_ids)->count();
                if($is_mobile >= 1){
                    throw new \Exception(__('手机号码已存在'));
                }
                
                Session::set('import_student', $insert);
            } catch (\Exception $exception) {
                $this->error($exception->getMessage());
            }
            
            if (!$insert) {
                $this->error(__('No rows were updated'));
            }
            
            $this->success('识别成功', '', ['count' => count($insert)]);
        }
        $this->error('错误的提交方式');
    }

    public function usercourse()
    {
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = Db::name('yalimedia_course_user')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        $this->view->assign('ids',input('ids'));
        return $this->view->fetch();
    }

    public function recharge()
    {
        if($this->request->isPost()){

            $data = $this->request->param('');
            $ids  = input('pid');
            $data = $data['row'];
            if(empty($data['nums']) || empty($data['taobaoorder'])){
                return $this->error('参数错误');
            }

            try{
                Db::startTrans();
                
                UserHistoryModel::addLog($ids,1,$data['nums'],$data['remark'],$data['taobaoorder']);
                UserModel::addNums($ids,$data['nums']);
                SysmessageModel::addLog($ids,'充值点评次数');

                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return ['code'=>1,'msg'=>'充值失败'.$e->getMessage()];
            }

            $this->success('充值成功',null,[]);
        }
        return $this->view->fetch();
    }
}
